<template>
  <div id="login_container" class="login_container">

    <div class="login_container__inner">
      <div class="left_bg" />
      <div class="right-form">
        <div class="form_main">
          <div class="title">用户登录</div>
          <div class="login_form">
            <el-form ref="loginRef" :model="loginForm" :rules="loginRules" >
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号"> </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码" @keyup.enter="handleLogin">
                </el-input>
              </el-form-item>
              <el-form-item prop="code">
                <div class="valid_code">
                  <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
                  </el-input>
                  <div class="login-code">
                    <img :src="codeUrl" class="login-code-img" @click="getCode" />
                  </div>
                </div>
              </el-form-item>
              <el-form-item style="width: 100%">
                <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
              </el-form-item>
              <el-form-item style="width: 100%">
                <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click="handleLogin">
                  <span v-if="!loading" class="text-white">登 录</span>
                  <span v-else class="text-white">登 录 中...</span>
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>


      </div>
    </div>


  </div>
</template>

<script setup lang="ts">
import { getCodeImg } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import leftImage from '@/assets/images/login_bg.png';

const userStore = useUserStore();
const router = useRouter();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const loginRef = ref<ElFormInstance>();

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        document.getElementById('login_container').classList.add('animate__fadeOutTopRight');
        document.getElementById('login_container').style.setProperty('--animate-duration', '0.5s');
        setTimeout(async () => {
          router.push('/');
          loading.value = false;
        }, 500);
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const loadingServe = ElLoading.service({
  lock: true,
  background: 'rgba(255, 255, 255, 0.7)'
});

onMounted(() => {
  const img = new Image();
  img.src = leftImage;
  img.onload = () => {
    loadingServe.close();
    // document.querySelector('.login-form').classList.add('login-form-show');
    getCode();
    getLoginData();
  };
});
</script>


<style rel="stylesheet/scss" lang="scss" scoped>
.login_container {
  width: 100%;
  height: 100%;
  display: flex;

  .login_container__inner {
    width: calc(100% - 40px);
    height: calc(100% - 40px);
    border-radius: 10px;
    border: 1px solid #dfe1e5;
    display: flex;
    margin: 20px;

    .left_bg {
      width: 60%;
      background-image: url('@/assets/images/login_bg.jpg');
      background-size: cover;
      border-top-left-radius: 10px;
      border-bottom-left-radius: 10px;
    }

    .right-form {
      height: 100%;
      width: 40%;
      position: relative;


      .form_main {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 400px;
        padding: 20px;

        .title {
          font-size: 30px;
          font-weight: bold;
          margin-bottom: 20px;
        }

        ::v-deep.el-button {
          height: 40px;
        }

        ::v-deep.el-input__inner {
          height: 40px;
          line-height: 40px;
        }

        ::v-deep.el-input__prefix {
          line-height: 40px;
        }

        ::v-deep.el-input__suffix {
          line-height: 40px;
        }

        .valid_code {
          height: 40px;
          display: flex;
          justify-content: space-between;

          .login-code {
            img {
              height: 40px;
            }
          }
        }
      }

    }
  }


}
</style>
